import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import '../state/comment_state.dart';
import '../state/user_state.dart';
import '../model/comment_model.dart';
import '../utils/my_common.dart';
import 'login_dialog_widget.dart';
import 'report_dialog.dart';
import 'custom_snackbar.dart';

/// 评论弹窗组件
class CommentDialogWidget extends StatefulWidget {
  final String postId;
  final VoidCallback? onCommentAdded;

  const CommentDialogWidget({
    super.key,
    required this.postId,
    this.onCommentAdded,
  });

  @override
  State<CommentDialogWidget> createState() => _CommentDialogWidgetState();
}

class _CommentDialogWidgetState extends State<CommentDialogWidget> {
  final CommentState _commentState = Get.find<CommentState>();
  final UserState _userState = Get.find<UserState>();
  final TextEditingController _commentController = TextEditingController();
  final FocusNode _commentFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    // 延迟聚焦，确保弹窗完全显示后再聚焦
    Future.delayed(Duration(milliseconds: 300), () {
      _commentFocusNode.requestFocus();
    });
  }

  @override
  void dispose() {
    _commentController.dispose();
    _commentFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.75,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      child: Column(
        children: [
          // 顶部标题栏
          _buildHeader(),

          // 评论列表
          Expanded(child: _buildCommentList()),

          // 底部输入框
          _buildCommentInput(),
        ],
      ),
    );
  }

  /// 构建顶部标题栏
  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.1),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 标题
          GetX<CommentState>(
            builder: (commentState) {
              final commentCount = _commentState.getPostCommentCount(
                widget.postId,
              );
              return Text(
                'Comments ($commentCount)',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w700,
                  color: Colors.black,
                ),
              );
            },
          ),

          // 关闭按钮
          GestureDetector(
            onTap: () => Get.back(),
            child: Container(
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: Colors.grey.withValues(alpha: 0.1),
                shape: BoxShape.circle,
              ),
              child: Icon(Icons.close, size: 20.sp, color: Colors.black54),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建评论列表
  Widget _buildCommentList() {
    return GetX<CommentState>(
      builder: (commentState) {
        final comments = _commentState.getPostComments(widget.postId);

        if (comments.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.chat_bubble_outline,
                  size: 48.sp,
                  color: Colors.grey[400],
                ),
                SizedBox(height: 16.h),
                Text(
                  'No comments yet',
                  style: TextStyle(fontSize: 16.sp, color: Colors.grey[600]),
                ),
                SizedBox(height: 8.h),
                Text(
                  'Be the first to comment!',
                  style: TextStyle(fontSize: 14.sp, color: Colors.grey[500]),
                ),
              ],
            ),
          );
        }

        return ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          itemCount: comments.length,
          itemBuilder: (context, index) {
            final comment = comments[index];
            return _buildCommentItem(comment);
          },
        );
      },
    );
  }

  /// 构建单个评论项
  Widget _buildCommentItem(CommentModel comment) {
    final user = _userState.getUserById(comment.userId);
    final userName = user?.nickname ?? user?.username ?? 'Unknown User';
    final userAvatar = user?.avatar ?? 'assets/images/avatar1.png';

    return Column(
      children: [
        Container(
          margin: EdgeInsets.only(top: 12.h, bottom: 12.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 第一行：头像、用户名和举报按钮
              Row(
                children: [
                  // 用户头像
                  CircleAvatar(
                    radius: 18.w,
                    backgroundImage: AssetImage(userAvatar),
                  ),

                  SizedBox(width: 12.w),

                  // 用户名
                  Expanded(
                    child: Text(
                      userName,
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.black,
                      ),
                    ),
                  ),

                  // 举报按钮
                  GestureDetector(
                    onTap: () => _handleReportComment(comment.id),
                    child: Icon(
                      Icons.report_gmailerrorred_rounded,
                      size: 26.sp,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),

              SizedBox(height: 8.h),

              // 第二行：评论内容
              Text(
                comment.content,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Color(0xFF999999),
                  height: 1.4,
                ),
              ),

              SizedBox(height: 8.h),

              // 第三行：时间和操作按钮
              Row(
                children: [
                  // 时间
                  Text(
                    _formatTime(comment.commentTime),
                    style: TextStyle(fontSize: 12.sp, color: Colors.grey[600]),
                  ),

                  Spacer(),

                  // 点踩按钮
                  GetX<CommentState>(
                    builder: (commentState) {
                      final isDisliked = commentState.isCommentDislikedByUser(
                        comment.id,
                      );
                      return GestureDetector(
                        onTap: () => _handleDislikeComment(comment.id),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Image.asset(
                              isDisliked
                                  ? 'assets/images/dislike_fill.png'
                                  : 'assets/images/dislike.png',
                              width: 16.w,
                              height: 16.w,
                            ),
                            SizedBox(width: 4.w),
                            Text(
                              comment.dislikeCount.toString(),
                              style: TextStyle(
                                fontSize: 12.sp,
                                color:
                                    isDisliked
                                        ? MyCommonUtils.orange
                                        : Colors.grey[600],
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),

                  SizedBox(width: 16.w),

                  // 点赞按钮
                  GetX<CommentState>(
                    builder: (commentState) {
                      final isLiked = commentState.isCommentLikedByUser(
                        comment.id,
                      );
                      return GestureDetector(
                        onTap: () => _handleLikeComment(comment.id),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Image.asset(
                              isLiked
                                  ? 'assets/images/good_fill.png'
                                  : 'assets/images/good.png',
                              width: 16.w,
                              height: 16.w,
                            ),
                            SizedBox(width: 4.w),
                            Text(
                              comment.likeCount.toString(),
                              style: TextStyle(
                                fontSize: 12.sp,
                                color:
                                    isLiked
                                        ? MyCommonUtils.orange
                                        : Colors.grey[600],
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ],
              ),
            ],
          ),
        ),

        // 分割线
        Container(
          height: 1,
          margin: EdgeInsets.only(left: 0.w, right: 0), // 与用户名对齐，右边不缩进
          color: Colors.grey.withValues(alpha: 0.2),
        ),
      ],
    );
  }

  /// 构建评论输入框
  Widget _buildCommentInput() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(color: Colors.grey.withValues(alpha: 0.2), width: 1),
        ),
      ),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Row(
          children: [
            // 输入框
            Expanded(
              child: TextField(
                controller: _commentController,
                focusNode: _commentFocusNode,
                decoration: InputDecoration(
                  hintText: 'Say something',
                  hintStyle: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[500],
                  ),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 12.h,
                  ),
                ),
                maxLines: null,
                textInputAction: TextInputAction.send,
                onSubmitted: (_) => _sendComment(),
              ),
            ),

            // 发送按钮
            GestureDetector(
              onTap: _sendComment,
              child: Container(
                margin: EdgeInsets.only(right: 8.w),
                width: 32.w,
                height: 32.w,
                child: Image.asset(
                  'assets/images/comment_send.png',
                  width: 32.w,
                  height: 32.w,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 发送评论
  void _sendComment() {
    final content = _commentController.text.trim();
    if (content.isEmpty) return;

    // 检查用户是否已登录
    if (!_userState.isLoggedIn) {
      Get.dialog(const LoginDialogWidget(), barrierDismissible: true);
      return;
    }

    // 添加评论
    _commentState.addPostComment(widget.postId, content);

    // 清空输入框
    _commentController.clear();

    // 回调
    widget.onCommentAdded?.call();

    // 显示成功提示
    CustomSnackBar.success('Your comment has been posted');
  }

  /// 处理点赞评论
  void _handleLikeComment(String commentId) {
    if (!_userState.isLoggedIn) {
      Get.dialog(const LoginDialogWidget(), barrierDismissible: true);
      return;
    }

    _commentState.likeComment(commentId);
  }

  /// 处理点踩评论
  void _handleDislikeComment(String commentId) {
    if (!_userState.isLoggedIn) {
      Get.dialog(const LoginDialogWidget(), barrierDismissible: true);
      return;
    }

    _commentState.dislikeComment(commentId);
  }

  /// 处理举报评论
  void _handleReportComment(String commentId) {
    Get.dialog(
      ReportDialogWidget(
        onReportSubmitted: (reportType) {
          // 处理举报提交
          _handleCommentReportSubmission(commentId, reportType);
        },
      ),
      barrierDismissible: true,
    );
  }

  /// 处理评论举报提交
  void _handleCommentReportSubmission(String commentId, String reportType) {
    // 删除评论
    _commentState.deleteComment(commentId);
  }

  /// 格式化时间
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inDays > 0) {
      return '${difference.inDays}d ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}h ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}m ago';
    } else {
      return 'Just now';
    }
  }
}
